package com.egao.common.module.outer.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.utils.ExcelUtils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.company.constants.CompanyConstants;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.vo.PreachCloudExcelVO;
import com.egao.common.module.company.entity.vo.PreachExcelVO;
import com.egao.common.module.company.service.impl.PreachCloudServiceImpl;
import com.egao.common.module.company.utils.CompanyUtil;
import com.egao.common.module.outer.entity.OuterPreach;
import com.egao.common.module.outer.entity.vo.OuterPreachExcelVO;
import com.egao.common.module.outer.mapper.OuterPreachMapper;
import com.egao.common.module.outer.service.OuterPreachService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 校外宣讲会接口实现类
 * @author pyx
 */
@Service
public class OuterPreachServiceImpl extends ServiceImpl<OuterPreachMapper, OuterPreach> implements OuterPreachService {

    private final Logger logger = LoggerFactory.getLogger(OuterPreachServiceImpl.class.getName());

    @Override
    public List<OuterPreach> listPage(PageParam<OuterPreach> pageParam) {
        //处理举办时间段数据
        pageParam = (PageParam<OuterPreach>) CompanyUtil.putApplyTime(pageParam);

        return baseMapper.listPage(pageParam);
    }

    @Override
    public JsonResult insertOuterPreach(OuterPreach outerPreach) {
        if (outerPreach == null) {
            throw new ParameterException("参数对象为空");
        }

        if (StrUtil.isBlank(outerPreach.getTitle())) {
            throw new ParameterException("标题不能为空");
        }
        if (StrUtil.isBlank(outerPreach.getOrganizer())) {
            throw new ParameterException("主办方不能为空");
        }
        if (StrUtil.isBlank(outerPreach.getHoldAddress())) {
            throw new ParameterException("举办地点不能为空");
        }
        if (outerPreach.getHoldTime() == null) {
            throw new ParameterException("举办时间不能为空");
        }

        baseMapper.insert(outerPreach);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult updateOuterPreach(OuterPreach outerPreach) {
        if (outerPreach == null) {
            throw new ParameterException("参数对象为空");
        }

        if (StrUtil.isBlank(outerPreach.getTitle())) {
            throw new ParameterException("标题不能为空");
        }
        if (StrUtil.isBlank(outerPreach.getOrganizer())) {
            throw new ParameterException("主办方不能为空");
        }
        if (StrUtil.isBlank(outerPreach.getHoldAddress())) {
            throw new ParameterException("举办地点不能为空");
        }
        if (outerPreach.getHoldTime() == null) {
            throw new ParameterException("举办时间不能为空");
        }

        baseMapper.updateById(outerPreach);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult deleteOuterPreach(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        if (removeById(id)) {
            return JsonResult.ok("删除成功");
        }

        return JsonResult.error("删除失败");
    }

    @Override
    public JsonResult getId(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        QueryWrapper<OuterPreach> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Integer count = baseMapper.selectCount(wrapper);

        if (count != 1) {
            throw new ParameterException("信息不存在");
        }

        OuterPreach outerPreach = baseMapper.selectById(id);
        return JsonResult.ok().setData(outerPreach);
    }

    @Override
    public List<OuterPreach> listPreach() {
        List<OuterPreach> listOuterPreach = new ArrayList<>();
        listOuterPreach = baseMapper.selectList(null);

        return listOuterPreach;
    }

    @Override
    public void exportExcel(Map<String, Object> page, HttpServletResponse response) {
        Object pageDataObj = page.get("pageData");
        HashMap<String, Object> hashMap = null;
        if (pageDataObj instanceof HashMap) {
            hashMap = (HashMap<String, Object>) pageDataObj;
        } else {
            logger.error("pageData 不是 HashMap 类型");
            return;
        }

        try {
            processHashMap(hashMap);
        } catch (BusinessException e) {
            logger.error("处理查询条件时出错: " + e.getMessage(), e);
            return;
        }
        page.put("pageData", hashMap);

        List<OuterPreachExcelVO> list = baseMapper.listExcel(page);

        String fileName = "outerPreach-" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try (OutputStream out = response.getOutputStream();
             ExcelWriter writer = ExcelUtil.getWriter(true)) {
            // 在第一行之前添加标题、总记录数、企业个数
            List<Object> titleRow = new ArrayList<>();
            if (hashMap.get("createTimeStart") != null && hashMap.get("createTimeEnd") != null) {
                titleRow.add(hashMap.get("createTimeStart").toString().split(" ")[0] + "~" + hashMap.get("createTimeEnd").toString().split(" ")[0] + "校外宣讲会信息");
            } else if (hashMap.get("createTimeStart") != null && hashMap.get("createTimeEnd") == null) {
                titleRow.add(hashMap.get("createTimeStart").toString().split(" ")[0] + "至今" + "校外宣讲会信息");
            } else if (hashMap.get("createTimeStart") == null && hashMap.get("createTimeEnd") != null) {
                titleRow.add("至" + hashMap.get("createTimeEnd").toString().split(" ")[0] + "校外宣讲会信息");
            } else {
                titleRow.add("校外宣讲会信息");
            }
            writer.writeRow(titleRow);

            // 获取总记录数和企业个数
            int totalCount = list.size();
            List<Object> totalRow = new ArrayList<>();
            totalRow.add("校外宣讲会总记录数: " + totalCount);
            writer.writeRow(totalRow);
            excelAddHeaderAlias(writer);
            writer.write(list, true);

            // 设置列自适应宽 必须在 write 以后
            ExcelUtils.autoColumnMaxSizeAll(writer.getSheet());
            writer.flush(out, true);
        } catch (IOException e) {
            logger.error("导出失败 - OuterPreachServiceImpl - exportExcel", e);
        }
    }

    /**
     * 为导出对象设置别名和排序 排序顺序为 add 顺序
     *
     * @param writer ExcelWriter
     */
    public void excelAddHeaderAlias(ExcelWriter writer) {
        writer.addHeaderAlias("title", "标题");
        writer.addHeaderAlias("organizer", "单位名称");
        writer.addHeaderAlias("holdTime", "举办时间");
        writer.addHeaderAlias("holdAddress", "举办地点");
    }

    /**
     * 实现时间段查询包含 timeEnd 当天记录，同时实现多单位、多岗位类型查询
     *
     * @param hashMap
     */
    private void processHashMap(HashMap<String, Object> hashMap) {
        // 发布时间查询
        if (hashMap.get("applyTime") != null) {
            String[] arr = hashMap.get("applyTime").toString().split("~");
            if (arr.length > 0) {
                hashMap.put("createTimeStart", arr[0] + " 00:00:00");
            }
            if (arr.length > 1) {
                hashMap.put("createTimeEnd", arr[1] + " 23:59:59");
            }
        }
    }

}
